var Acceleration = cc.Class({
    name: 'Acceleration',
    properties: {
        ax: 0,
        ay: 0,
        az: 0,
        last_update: 0,
        callback: null,
        target: null,
        id: 0
    },

    addListener: function (callback, target, tick) {
        tick = tick || (1000 / 60);
        this.callback = callback;
        this.target = target;
        this.ax = 0.001;
        this.ay = 0.001;
        this.az = 0.001;
        this.last_update = 0;
        this.baky = null;

        var self = this;
        var deviceMotionHandler = function (eventData) {
            var acceleration = eventData.accelerationIncludingGravity;
            var curTime = new Date().getTime();
            if ((curTime - self.last_update) > 60 && acceleration.x) {
                var diffTime = curTime - self.last_update;
                self.last_update = curTime;
                if(self.baky == null) self.baky = acceleration.y;
                
                self.ax = acceleration.x;
                self.ay = acceleration.y - self.baky;
                self.az = acceleration.z;

            }
        };
        window.addEventListener('devicemotion', deviceMotionHandler, false);

        var self = this;
        this.id = window.setInterval(function () {
            self.callback.call(self.target, Math.floor(self.ax * 10), Math.floor(self.ay * 10), Math.floor(self.az * 10));
        }, tick);
    },



    removeListener: function () {
        window.removeEventListener('devicemotion', this.deviceMotionHandler, false);
        window.clearInterval(this.id);
    }
});

module.exports = Acceleration;